package com.hns.can.master.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;

import com.hns.can.master.component.ParseCarInfoExcel;
import com.hns.can.master.component.ParseDriverInfoExcel;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.tool.pub.*;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.addressing.EndpointReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.web.BaseController;
import com.hns.can.master.entity.BaseCarInfoEntity;
import com.hns.can.master.entity.BaseDrvInfoEntity;
import com.hns.can.master.service.BaseCarInfoService;
import com.hns.can.master.service.BaseDrvInfoService;
import com.hns.can.master.service.WebServiceBSService;
import com.hns.can.master.vo.CarPostDataVo;
import com.hns.can.master.vo.LockCarParamVo;
import com.hns.frame.mybatis.Pagination;
import com.hns.tool.export.ExportUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 车辆信息维护控制类
 * @author:lan
 * @email:763836737@qq.com
 * @version Revision 2.0.0
 */
@Controller
@RequestMapping("/baseCarInfo")
public class BaseCarInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(BaseCarInfoController.class);
    private static String ClientURL = UtilConfig.getString("eqwebserver_url");
    
    /**
     * 车辆信息service
     */
	@Autowired
    private BaseCarInfoService baseCarInfoService;
	
	@Autowired
	private WebServiceBSService webServiceBSService;
	
	@Autowired
    private  BaseDrvInfoService baseDrvInfoService;
	
	/**
	 * 导出文件表头
	 */
	private final String[] tableHeaderNames={"车牌号","车辆编号","所属机构","车辆类型","车辆型号","燃油类型","生产厂家","购置日期","车架号(VIN)码","发动机厂家","发动机型号","标准能耗","电池续航里程"};
	/**
	 * 导出文件字段名
	 */
    private final String[] tableHeaderFields={"licPltNo","carInCd","organName","carType","carModel","flOilType","produceFacty","prchDate","frameNo","engiFacty","engiModel","refrEnerCons","bteryEnduranceMile"};

	/**
	 * 添加一个车辆
	 * @param entity
	 * @return
	 * @throws Exception
	 * @author:lan
	 * @email:763836737@qq.com
	 */
    @RequestMapping("/addCarInfo")
    @ResponseBody
    public Object addCarInfo(BaseCarInfoEntity entity) throws Exception {
        baseCarInfoService.addCarInfo(entity, this.getCurrentUser().getUser());
        return this.getReturnMsg("您成功添加一个车辆");
    }
    
    /**
     * 得到车辆的page对象
     * @param dataVo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/searchCarInfoPage")
    @ResponseBody
    public Object searchCarInfoPage(CarPostDataVo dataVo) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        dataVo.setUserId(user.getId());
        Pagination page = baseCarInfoService.searchCarInfoPage(dataVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 导出车辆信息excel
     * @param dataVo
     * @param response
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/exportCarInfoExcel")
    public void exportCarInfoExcel(CarPostDataVo dataVo, HttpServletResponse response) throws Exception {
        dataVo.setUserId(this.getCurrentUser().getUser().getId());
    	List<BaseEntity> list = baseCarInfoService.getCarInfoList(dataVo);
    	ExportUtil.exportFiles(Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, response, "excel", "carInfo", "车辆基础信息");
    }
    
    
    /**
     * 导出车辆信息pdf
     * @param dataVo
     * @param response
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/exportCarInfoPdf")
    @ResponseBody
    public void exportCarInfoPdf(CarPostDataVo dataVo, HttpServletResponse response) throws Exception {
    	dataVo.setUserId(this.getCurrentUser().getUser().getId());
    	List<BaseEntity> list = baseCarInfoService.getCarInfoList(dataVo);
    	ExportUtil.exportFiles(Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, response, "pdf", "carInfo", "车辆基础信息");
    }
    
    /**
     * 根据车辆id求车辆信息
     * @param carId
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getCarInfoByCarId")
    @ResponseBody
    public Object getCarInfoByCarId(@RequestParam(value="carId") String carId) throws Exception {
    	BaseEntity entity = baseCarInfoService.getCarInfoByCarId(carId);
        return this.getReturnResult(entity);
    }
    
    /**
     * 更新车辆的信息
     * @param entity
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/uptCarInfo")
    @ResponseBody
    public Object uptCarInfo(BaseCarInfoEntity entity) throws Exception {
        baseCarInfoService.uptCarInfo(this.getCurrentUser().getUser(), entity);
        return this.getReturnMsg("保存成功");
    }
    
    /**
     * 删除一个车辆
     * @param carIds
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/delCarInfo")
    @ResponseBody
    public Object delCarInfo(@RequestParam(value="carIds") String[] carIds) throws Exception {
        baseCarInfoService.delCarInfo(this.getCurrentUser().getUser(), carIds);
        return this.getReturnMsg("删除成功");
        
    }
    /**
     * 查询绑定信息
     * @param carIds
     * @return
     * @throws Exception
     * @author:xy
     */
    @RequestMapping("/findBangInfo")
    @ResponseBody
    public Object findBangInfo(@RequestParam(value="carIds") String[] carIds) throws Exception {
        int count= baseCarInfoService.findBangInfo(carIds);
//        if(count > 0){
//            throw new BusinessException(MsgType.WARN.getFlag(), "不同版本，相同启用时间、相同日期类型（工作日、周末、通用）时，您输入的时间不能有交集");
//        }
        return this.getReturnResult(count);
    }
    /**
     * 根据BaseCarInfoEntity获取车辆列表
     * @param entity
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getBaseCarInfoList")
    @ResponseBody
    public Object getBaseCarInfoList(BaseCarInfoEntity entity) throws Exception {
    	List<BaseCarInfoEntity> list = baseCarInfoService.getBaseCarInfoList(entity);
        return this.getReturnResult(list);
    }
    
    /**
     * <!-- 设备关联车辆    过滤已关联车辆 -->
     * @param entity
     * @return
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/getBaseCarInfoListForEq")
    @ResponseBody
    public Object getBaseCarInfoListForEq(BaseCarInfoEntity entity) throws Exception {
        List<BaseCarInfoEntity> list = baseCarInfoService.getBaseCarInfoListForEq(entity);
        return this.getReturnResult(list);
    }
    
    /**
     * 发送锁车指令
     * @param lockCarParamVo
     * @return
     * @throws Exception
     * @author:lan
     * @email:763836737@qq.com
     */
    @RequestMapping("/uptCarLockStatus")
    @ResponseBody
    public Object uptCarLockStatus(LockCarParamVo lockCarParamVo) throws Exception {
    	String lockCarJson=JsonUtil.getJsonStringFromObject(lockCarParamVo);
    	logger.error("锁车指令:"+lockCarJson);
    	Object[] result=webServiceBSService.sendToCommModel(lockCarJson, "07");
        return this.getReturnResult(result!=null?result[0]:"");
    }
    
    @RequestMapping("/getDrvName")
    @ResponseBody
    public Object getDrvName(LockCarParamVo lockCarParamVo,HttpServletRequest request, HttpServletResponse response) throws Exception {
    	String drv_name="";
    	try{
	    	BaseCarInfoEntity baseCarInfoEntity=(BaseCarInfoEntity) baseCarInfoService.getCarInfoByCarId(
	    			lockCarParamVo.getCarId());
	    	String sysEaiId=baseCarInfoEntity.getSyseaiId();
	    	HashMap<String,String> paramMap=new HashMap<String,String>();
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
	    	paramMap.put("bus", sysEaiId);
	    	paramMap.put("date", sdf.format(new Date()));
	    	Long begintime=System.currentTimeMillis();
	    	OMElement resultOM=webServiceBSService.getDataSetByNetClient(paramMap, "QueryDriverCheckInByDate", 
	    			new EndpointReference(ClientURL));
	    	Long endtime=System.currentTimeMillis();
	    	logger.debug("调用实时驾驶员服务花费时间:"+(endtime-begintime));
	    	String drv_no="";
	    	 Iterator<OMElement> iter = resultOM.getChildElements();  
	         while(iter.hasNext()){  
	             OMElement node = iter.next();  
	             if(node.getLocalName().equals("QueryDriverCheckInByDateResult")){
	                 Iterator<OMElement> iter1 = node.getChildElements();  
	                 while(iter1.hasNext()){  
	                     OMElement node1 = iter1.next();  
	                     if(node1.getLocalName().equals("diffgram")){ 
	                     	 Iterator<OMElement> iterdDiffgram = node1.getChildElements();  
	                          while(iterdDiffgram.hasNext()){  
	                         	 OMElement nodeTable = iterdDiffgram.next();  
	 		                    Iterator<OMElement> ite =nodeTable.getChildrenWithName(new QName("table1"));
					            while(ite.hasNext()){  
					            	OMElement nodeOM=ite.next();
					            	drv_no=nodeOM.getFirstChildWithName(new QName("司机")).getText();
					            }
	                          }
	                     }
	                 }
	             }
	         }
	         BaseDrvInfoEntity entity=new BaseDrvInfoEntity();
	         entity.setWorkEmpeEmpno(drv_no);
	         List<BaseDrvInfoEntity> baseDrvList=baseDrvInfoService.getBaseDrvInfoList(entity);
	         if(!PubUtil.isEmpty(baseDrvList)){
	        	 BaseDrvInfoEntity baseDrvInfoEntity=baseDrvList.get(0);
	        	 drv_name=baseDrvInfoEntity.getDrvName();
	         }
    	}catch(Exception e){
    		logger.error("驾驶员获取出错："+e.getMessage(),e);
    	}
        //ResponseUtil.responseJSON(drv_name, response);
        return this.getReturnResult(drv_name);
    }

    /**
     * 上传车辆信息
     * @param carInfoFile
     * @param request
     * @return
     * @throws Exception
     * @author:Chenl
     * @email:370238764@qq.com
     */
    @RequestMapping(value = "/uploadCarInfoFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadElePaperFile(
            @RequestParam MultipartFile carInfoFile,
            HttpServletRequest request,String organId,HttpServletResponse response) throws Exception {
        // 将excel文件存盘
        String oldFileName = carInfoFile.getOriginalFilename();
        String newFileName = UtilString.getUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/temp/";
        FileUploadUtil.uploadFile(carInfoFile.getInputStream(), newFileName, targetPath);
        // 解析excel文件得到list对象
        String fileName = targetPath + newFileName; // 完整路径
        File file = new File(fileName);
        SysUserEntity user = this.getCurrentUser().getUser();
        List<BaseCarInfoEntity> list = ParseCarInfoExcel.parseExcelToList(file);
        if(PubUtil.isEmpty(list)){
            ResponseUtil.responseJSON("您导入的模版有误。", response);
        }
        //存入对应库表
        String msgs = baseCarInfoService.saveCarInfoToDB(list,user,organId);
        int successCnt = baseCarInfoService.getSuccessCount();
        // 删除临时文件
        FileUploadUtil.delFile(fileName);
        msgs = ",失败"+(list.size()-successCnt)+"条,<br/> 失败:<br/> "+msgs;
        if(successCnt == list.size()){
            msgs = "";
        }
        ResponseUtil.responseJSON(this.getReturnMsg("总共"+list.size()+"条站点数据,成功导入"+successCnt+"条"+msgs),response);
        return null;
    }

    /**
     * 导出站点经纬度模版
     * @return
     * @throws Exception
     * @author: chenl
     * @email:370238764@qq.com
     */
    @RequestMapping("/exportCarInfoTemplate")
    @ResponseBody
    public void exportStationInfoTemplate(HttpServletResponse response) throws Exception {
//        List<BaseEntity> list = new ArrayList<BaseEntity>();
//        ExportUtil.exportFiles(Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, response, "excel", "stationInfo", "站点信息");
        String fileName = "carInfoTemplate.xlsx";
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/" + fileName;
        File tempFile = new File(targetPath);
        if(!tempFile.exists()){
            throw new BusinessException(MsgType.WARN.getFlag(), "没有模版可以下载！");
        }
        ExportUtil.GeneratoDownFile(targetPath, fileName.substring(0,fileName.lastIndexOf('.')),".xlsx",response);
    }
}
